package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wenjingyuan
 * @Date: 2023/09/24/20:06
 * @Description:
 */
@Api(tags = "板块接口")
@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {
    //从配置文件中获取，如果配置文件中没有获取那么取默认值9
    @Value("${bit-forum.index.board-num:9}")
    private Integer indexBoardNum;

    @Resource
    private IBoardService boardService;
    /**
     * 查询首页版块列表
     * @return
     */
    @GetMapping("/topList")
    @ApiOperation("获取首页版块列表")
    public AppResult<List<Board>> topList(){
        log.info("首页板块的个数是"+indexBoardNum);
        //调用service接口
        List<Board> boards = boardService.selectByNum(indexBoardNum);
        //判断是否为空
        if(boards==null){
            boards=new ArrayList<>();
        }
        //返回结果
        return  AppResult.success(boards);
    }
    @ApiOperation("根据板块ID获取每个版块下的版块列表")
    @GetMapping("/getById")
    public AppResult getById(@ApiParam("板块ID") @RequestParam("id") @NonNull Long id){
        //直接调用service接口
        Board board = boardService.selectById(id);
        if(board==null || board.getDeleteState()==1){
            //判断板块的有效性
            //打印日志
            log.warn(ResultCode. FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_BOARD_NOT_EXISTS));
        }
        return AppResult.success(board);
    }
}
